package com.bankapp.service.bank;

import com.bankapp.domain.bank.Email;

import java.io.Closeable;

public class EmailService implements Closeable {
    private volatile boolean running;
    private EmailQueue emailQueue;
    private Thread thread;

    public EmailService() {
        running = true;
        emailQueue = new EmailQueue();

        thread = new Thread() {
            @Override
            public void run() {
                while (running || !emailQueue.isEmpty())
                    sendEmail(emailQueue.getEmail());
            }
        };
    }

    public void start() {
        thread.start();
    }

    public void sendNotificationEmail(Email email) {
        if (!running)
            throw new IllegalStateException("You cannot send email notifications");

        emailQueue.add(email);
    }

    private void sendEmail(Email email) {
        if (email != null) {
            System.out.println(email + " was sent");
        }
    }

    @Override
    public void close() {
        running = false;
        thread.interrupt();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
